<template>
  <el-dialog class="public-dialog" :title="config.title" width="1600" :modelValue="modelValue" @close="handleClose" draggable align-center :close-on-click-modal="false">
    <div v-html="config.header"></div>
    <div class="flex border-card my-[8px]" :loading="loading">
      <div class="w-[54px] border-right">
        <div class="border-bottom">序号</div>
        <div class="p-[4px] pt-[9px]">
          <div v-for="(i, key) in list" :key="key">
            {{ key + 1 }}
          </div>
        </div>
      </div>
      <div class="flex-1">
        <div class="border-bottom">
          <span v-for="item in config.columns" :key="item.label" :style="{ width: item.width + 'px' }" class="inline-block">
            {{ item.label }} <span v-if="item.required" class="text-red">*</span>
          </span>
          <!-- <span class="mr-[46px]">系统订单号</span> <span>海外仓出库单号</span> -->
        </div>
        <div class="p-[4px]">
          <el-input v-model="textarea" :autosize="{ minRows: 10 }" class="w-[100%]" show-word-limit type="textarea" @input="inputChange" @keydown.tab.prevent="tabInput" id="my-input-tab" />
        </div>
      </div>
    </div>

    <el-table :data="tableData" class="w-[100%] mt-[8px]" v-if="tableData.length != 0" :row-style="rowStyle">
      <el-table-column v-for="item in config.columns" :key="item.value" :prop="item.value" :label="item.label" :min-width="item.width" />
      <el-table-column prop="create_time" label="上传时间" width="140" />
      <el-table-column prop="error_msg" label="上传结果" width="140">
        <template #default="{ row }">
          {{ row.status_val }}
          <span v-if="row.status == 2"> ：{{ row.error_msg }} </span>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="loading"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus"
import api from "../../api"
const props = defineProps({})
const modelValue = ref(false)

const emit = defineEmits(["refresh", "submit"])

const loading = ref(false)

const textarea = ref("")
const tabInput = (e) => {
  let input = document.getElementById("my-input-tab")
  let start = input.selectionStart
  textarea.value = textarea.value.substring(0, start) + "     " + textarea.value.substring(start)
  setTimeout(() => {
    // 移动光标位置
    input.setSelectionRange(start + 5, start + 5)
  }, 1)
}
const list = ref([])
const inputChange = (e) => {
  let data = e.split("\n")?.map((v) => v?.split(" ")?.filter(Boolean)?.join("\t"))
  data = data?.map((v) => v?.split("\t")?.filter(Boolean))
  if (data.length > 200) {
    data.length = 200
    let val = e.split("\n")
    val.length = 200
    textarea.value = val.join("\n")
  }
  list.value = data
}

const handleSave = async () => {
  try {
    let data = list.value?.filter((v) => v.length)
    let index = data?.findIndex((v) => v.length < config.value.columns.filter((v) => v.required)?.length)
    if (index == -1) {
      let params = {
        tracing_number: data.map((v) => {
          let obj = {}
          config.value.columns.map((item, i) => {
            obj[item.value] = v[i] || ""
          })
          return obj
        }),
      }
      // console.log(params)
      loading.value = true

      config.value
        .save(params)
        .then((res) => {
          loading.value = false
          setTimeout(() => {
            config.value?.getHistory().then((res) => {
              if (res.data.find((v) => v.status == 2)) {
                tableData.value = res.data
              } else {
                ElMessage.success("上传成功")
                handleClose()
              }
            })
          }, 500)
        })
        .catch(() => {
          loading.value = false
        })
    } else {
      ElMessage({ showClose: true, message: `第${index + 1}条数据格式有误！`, type: "warning" })
    }
  } catch (e) {
    console.error(e)
  } finally {
  }
}

const config = ref({
  title: "",
  header: "",
  columns: [],
  save: () => {},
  getHistory: () => {},
})
const rowStyle = ({ row }) => {
  if (row.status == 2) {
    return { color: "red" }
  }
}
const tableData = ref([])
const open = (param) => {
  config.value = param
  modelValue.value = true
  config.value?.getHistory({ pageSize: 999999 }).then((res) => {
    tableData.value = res.data
  })
}
const handleClose = (refresh) => {
  modelValue.value = false
  // getOutNumber
  textarea.value = ""
  list.value = []
  tableData.value = []
  loading.value = false
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped>
.border-card {
  border: 1px solid #c8c8c8;
}
.border-right {
  border-right: 1px solid #c8c8c8;
}
.border-bottom {
  border-bottom: 1px solid #c8c8c8;
  padding: 8px;
}
</style>
